import querystring from "querystring";
import settings from "@/settings"

export const getAuthen = function () {
  const search = window.location.search
 /**
 * 这一段作用是先跳转网页后再跳转
 **/
  if (search !== '') {
    const search = querystring.parse(window.location.search.replace("?", ''))
    let appIdPromise
    // 有enterpriseId
    if (!!search.enterpriseId) {
      $nuxt.$store.commit("authen/setEnterpriseId", search.enterpriseId)
    } else {
      alert('你没有传递站点参数');
    }
    // 有appId
    if (!!search.appId) {
      $nuxt.$store.commit("authen/setAppId", search.appId)
      appIdPromise = Promise.resolve();
    } else {
      appIdPromise = $nuxt.$store.dispatch('authen/getAppId', search.enterpriseId).then((res) => {
        $nuxt.$store.commit("authen/setEnterpriseId", res.enterpriseId)
      })
    }

    // 拿到当前地址 
    const path = window.location.pathname === "/authen" ? "/" : window.location.pathname
    // 替换为自己的标识符号
    const searchStr = window.location.search.replace("?", ".").replace(/&/g, "-").replace(/=/g, "_")

    appIdPromise.then(() => {
      window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + $nuxt.$store.getters["authen/appId"] + "&redirect_uri=" + settings.gotoUrl + "%2fauthen&response_type=code&scope=snsapi_base&state=" + path + searchStr + "#wechat_redirect"
    })
  } else {
    alert("请传递站点参数")
  }
}
